import { container } from "tsyringe"
import { ROOT } from "./tokens"
import { dirname, join } from "path"
import { ensureDirSync, readFileSync, writeFileSync } from "fs-extra"
import { fromUint8Array } from 'js-base64';
import { randomFillSync } from "crypto";
import dayjs from 'dayjs';
export function now() {
    return dayjs();
}
export const generateRandomString = (length = 64) => fromUint8Array(randomFillSync(new Uint8Array(length)), true);

export function generateTimestapString(length: number = 6) {
    const _now = now();
    return `${_now.format('YYYYMMDDHHmm')}${generateRandomNumber(length)}`;
}

export function generateRandomNumber(length: number = 6) {
    const min = Math.pow(10, length);
    const max = Math.pow(10, length + 1) - 1;
    const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
    return randomNumber.toString();
}

export function unique<T>(list: T[], key: (data: T) => string | number) {
    const uniList: T[] = [];
    const keys = new Set<string | number>()
    list.map(it => {
        const _key = key(it)
        if (keys.has(_key)) {
            return;
        }
        keys.add(_key)
        uniList.push(it)
    })
    keys.clear();
    return uniList;
}


export const loadData = <T>(file: string, def: T): T => {
    try {
        const content = readFileSync(file, 'utf-8')
        return JSON.parse(content)
    } catch (e) {
        return def
    }
}

export const useData = <T>(file: string, def: T) => {
    const root = container.resolve(ROOT)
    const filePath = join(root, file)
    ensureDirSync(dirname(filePath))
    const data = loadData<T>(filePath, def)
    return {
        data,
        setData: (val: any) => {
            writeFileSync(filePath, JSON.stringify(val, null, 2))
        }
    }
}